package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.FDDUtils
import cn.com.kh.HttpClientProxy
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.batch.FCallAPI_Utils
import cn.com.kh.result.iAPIResult
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiBatchAuthTask
 * @Description: 定时获取法大大状态
 *
 */
public class apiBatchFddStateTask implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiBatchFddStateTask.class);
    private static String CC_APIDomain = "https://ronglian.dbc61.com/ngsapitask_ph/api";
    private static String APPID = "100002";
    private static String APPKEY = "E4uX9c65e5h7A5K5DA6rw6JL";

    // 获取数据库操作对象
    private static JdbcTemplate jt = new JdbcTemplate();

    // 批次启动暂停的控制Map
    private volatile static Map<String, Integer> stopFlagMap = new HashMap<String, Integer>();

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        long startTime = System.currentTimeMillis();

        jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject res_Json = iAPIResult.ERROR("获取-定时获取法大大状态 失败");

        String method = request.getMethod();
        log.debug("获取请求方式：" + method);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String callPram = "";
        if (method.equals("GET")) {
            callPram = request.getQueryString();
            log.info("接收调用GET参数信息：" + callPram);
        } else if (method.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callPram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + callPram);
        }

        try {
            // 获取操作数据源
            jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取待认证客户状态
            res_Json = batchFDDCustFix();

        } catch (Exception e) {
            res_Json = iAPIResult.ERROR("定时获取法大大状态 处理调用异常(" + e.getMessage() + ")");
            log.error("定时获取法大大状态 处理调用异常：" + e.getMessage(), e);

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "定时获取法大大状态", "apiBatchFddStateTask", callPram, res_Json.toString(), (System.currentTimeMillis() - startTime).toString(), method + ":" + mapParam.toString());
        }

        log.debug("定时获取法大大状态 执行结果：" + res_Json.toString());
        return res_Json.toString();
    }


    // Fix-1-获取待认证客户客户
    public static JSONObject batchFDDCustFix() throws InterruptedException {
        JSONObject res_Json = iAPIResult.ERROR("推送-获取待认证客户客户 失败");
        String dealSQL = "Select R1.Oper_Id, R1.Rec_Guid, R1.Customer_Id, R1.Customer_Guid, R1.Fdd_Customer_Id, R1.Push_Type, R1.Status, R1.Statusdesc, R2.Customername, R2.Mobile, R2.Customertype, R2.Customerid From Sys_Oper_Log_Auth R1 Left Join Customer R2 On R1.Customer_Guid = R2.Customer_Guid Where (R1.Status != If(Ifnull(R2.Customertype, '个人') = '公司', '4', '2') Or R1.Status Is Null Or R1.Status = '') And R1.Push_Time > Date_Add(Now(), Interval -30 Day) Order By R1.Push_Time Desc";
        List<Map<String, Object>> selectCus = jt.queryForList(dealSQL);
        log.debug("Fix-法大大客户基础信息 :" + selectCus.size());

        int total_Num = selectCus.size();
        int succ_Num = 0;
        int fail_Num = 0;
        // 处理节点数据
        for (Map<String, Object> CusMap : selectCus) {
            String Oper_Id = KHUtil.GetMapV(CusMap, "Oper_Id");
            String Rec_Guid = KHUtil.GetMapV(CusMap, "Rec_Guid");
            String Fdd_Customer_Id = KHUtil.GetMapV(CusMap, "Fdd_Customer_Id");
            String Customer_Guid = KHUtil.GetMapV(CusMap, "Customer_Guid");
            String Customername = KHUtil.GetMapV(CusMap, "Customername");
            String Customerid = KHUtil.GetMapV(CusMap, "Customerid");
            String Mobile = KHUtil.GetMapV(CusMap, "Mobile");
            String Customertype = KHUtil.GetMapV(CusMap, "Customertype");
            Customertype = KHUtil.isNull(Customertype) ? "个人" : Customertype;
            try {
                // 检查当前客户最新认证状态
                if (Customertype.equals("个人")) {
                    JSONObject get_Json = FCallAPI_Utils.getFDDPersonInfo(jt, Rec_Guid, Mobile);
                    log.error("ℹ获取[个人认证][" + Rec_Guid + "]法大大客户基础信息 结果：" + get_Json);

                    if (KHUtil.GetSFJV(get_Json, "code").equals("1") && KHUtil.GetSFJV(get_Json.getJSONObject("data"), "code").equals("1") && KHUtil.GetSFJV(get_Json.getJSONObject("data").getJSONArray("data").getJSONObject(0), "verifiedStatus").equals("2")) {
                        get_Json = SendCert_Callback(Rec_Guid, Customerid, "审核通过", "个人认证");
                        log.error("✅获取[个人认证][" + Rec_Guid + "]模拟回调 结果：" + get_Json);
                        succ_Num++;
                    } else {
                        fail_Num++;
                    }
                } else {
                    JSONObject get_Json = FCallAPI_Utils.getFDDCompanyInfo(jt, Rec_Guid, Customername);
                    log.error("ℹ获取[企业认证][" + Rec_Guid + "]法大大客户基础信息 结果：" + get_Json);
                    fail_Num++;

                }
            } catch (Exception e) {
                log.error("⛔检查当前客户最新认证状态 异常", e);

            }

            Thread.sleep(200);

        }

        res_Json = iAPIResult.SUCCESS("获取待认证客户状态End", "total_Num:" + total_Num + " succ_Num:" + succ_Num + " fail_Num:" + fail_Num);
        return res_Json;

    }

    // Fix-2-模拟认证回调
    public static JSONObject SendCert_Callback(String recGuid, String customerId, String statusDesc, String authType) {

        JSONObject res_Json = iAPIResult.ERROR("推送-模拟认证回调 失败");
        try {

            JSONObject jsonPara = new JSONObject();
            jsonPara.put("customerId", customerId);
            jsonPara.put("statusDesc", statusDesc);

            if (statusDesc.equals("审核通过")) {
                jsonPara.put("status", "2");
                jsonPara.put("auditFailReason", "");
            } else {
                jsonPara.put("status", "1");
                jsonPara.put("auditFailReason", "模拟回调认证失败");

            }

            JSONObject jsons = FDDUtils.getCallBody(APPID, APPKEY, jsonPara.toString());
            log.debug("模拟认证回调 参数:" + jsons.toString());

            String callResStr = HttpClientProxy.sendPost(CC_APIDomain + "/apiBatchSignMain?callbackType=" + KHUtil.encode(authType) + "&customerId=" + customerId + "&recGuid=" + KHUtil.encode(recGuid), jsons.toString(), "", 0);
            res_Json = JSONObject.fromObject(callResStr);
            log.debug("模拟认证回调 结果:" + callResStr);

        } catch (Exception e) {
            log.error("模拟认证回调 异常", e);

        }
        return res_Json;

    }
}